package wei.qiang.ye.springsecuritydemo.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.stereotype.Service;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Service
public class MyAuthenticationSucessHandler implements AuthenticationSuccessHandler {
    //Spring Security提供的用于缓存请求的对象，通过调用它的getRequest方法可以获取到本次请求的HTTP信息
    private RequestCache requestCache = new HttpSessionRequestCache();
    //DefaultRedirectStrategy的sendRedirect为Spring Security提供的用于处理重定向的方法
    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

     @Autowired
     private ObjectMapper mapper;

    /**
     *
     * @param request
     * @param response
     * @param authentication Authentication参数既包含了认证请求的一些信息，比如IP，请求的SessionId等，也包含了用户信息
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
        //印出Authentication对象的信息
//        response.setContentType("application/json;charset=utf-8");
//        response.getWriter().write(mapper.writeValueAsString(authentication));

        //重定向页面 登录成功后页面将跳转回引发跳转的页面
//        SavedRequest savedRequest = requestCache.getRequest(request, response);
//        redirectStrategy.sendRedirect(request, response, savedRequest.getRedirectUrl());


        redirectStrategy.sendRedirect(request, response, "/index");
    }
}
